import React, { useState, useEffect } from 'react';
import '../styles/roleManage.css';
import { Input, Button } from 'antd';
import { Space, Table, Tag, Select, Modal } from 'antd';
import type { TableProps } from 'antd';
import axios from '../axios';

export default function roleManage() {
  interface DataType {
    index: number;
    name: String;
    organization: String;
    buildtime: Date;
    changetime: Date;
    count: Number;
    desc: String;
    status: Boolean;
  }

  const columns: TableProps<DataType>['columns'] = [
    {
      title: '序号',
      dataIndex: 'index',
      key: 'index',
    },
    {
      title: '角色',
      dataIndex: 'name',
      key: 'name',
    },
    {
      title: '部门',
      dataIndex: 'organization',
      key: 'organization',
    },
    {
      title: '人数',
      dataIndex: 'count',
      key: 'count',
    },
    {
      title: '创建时间',
      dataIndex: 'buildtime',
      key: 'buildtime',
    },
    {
      title: '修改时间',
      dataIndex: 'changetime',
      key: 'changetime',
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      render: (_, { status }) => (
        <>
          {status ? (
            <span style={{ color: 'green' }}>已启用</span>
          ) : (
            <span style={{ color: 'red' }}>已停用</span>
          )}
        </>
      ),
    },
    {
      title: '操作',
      key: 'action',
      render: (_, record) => (
        <Space size="middle">
          <a
            onClick={() => {
              edit(record);
            }}
          >
            编辑
          </a>
          <a
            onClick={() => {
              del(record);
            }}
          >
            删除
          </a>
          <a>
            {record.status ? (
              <a
                onClick={() => {
                  falseStatus(record);
                }}
              >
                停用
              </a>
            ) : (
              <a
                onClick={() => {
                  trueStatus(record);
                }}
              >
                启用
              </a>
            )}
          </a>
        </Space>
      ),
    },
  ];

  const [organizations, setOrganizations] = useState([]);
  const getOrganization = async () => {
    let {
      data: { code, data },
    } = await axios.get('ljt_getOrganization');
    if (code === 200) {
      let copy: any = [...organizations];
      data.forEach((item: any) => {
        copy.push({
          value: item._id,
          label: item.name,
        });
      });
      setOrganizations(copy);
    }
  };

  const [data, setData] = useState<DataType[]>([]);
  const getData = async () => {
    let {
      data: { code, roles },
    } = await axios.get('ljt_getRoles', {
      params: {
        name: searchName,
        oid: searchOrganization,
      },
    });
    console.log(111, roles);

    if (code === 200) {
      let rolelist: any = [];
      roles.forEach((item: any, index: number) => {
        rolelist.push({
          id: item._id,
          index: index + 1,
          name: item.name,
          organization: item.oid.name,
          oid: item.oid._id,
          buildtime: item.buildtime.split('T')[0],
          changetime: item.changetime.split('T')[0],
          count: item.count,
          desc: item.desc,
          status: item.status,
        });
      });
      setData(rolelist);
    }
  };

  const [modal2Open, setModal2Open] = useState(false);
  const { TextArea } = Input;
  const [name, setName] = useState('');
  const [organization, setOrganization] = useState('请选择部门');
  const [count, setCount] = useState('');
  const [desc, setDesc] = useState('');
  const [status, setStatus] = useState(true);

  const submit = async () => {
    if (flag) {
      let obj = {
        name,
        oid: organization,
        changetime: new Date(),
        count,
        desc,
        status,
      };
      let {
        data: { code, msg },
      } = await axios.post('ljt_updateRole', { id, obj });
      if (code === 200) {
        setModal2Open(false);
        getData();
      }
    } else {
      let obj = {
        name,
        oid: organization,
        buildtime: new Date(),
        changetime: new Date(),
        count,
        desc,
        status,
      };
      let {
        data: { code, msg },
      } = await axios.post('ljt_addRole', obj);
      if (code === 200) {
        setModal2Open(false);
        getData();
      }
    }
    setName('');
    setOrganization('请选择部门');
    setCount('');
    setDesc('');
    setStatus(true);
    setId('');
    setFlag(false);
  };
  const cancel = () => {
    setModal2Open(false);
    setName('');
    setOrganization('请选择部门');
    setCount('');
    setDesc('');
    setStatus(true);
    setFlag(false);
  };

  const [flag, setFlag] = useState(false);
  const [id, setId] = useState('');
  const edit = (item: any) => {
    setId(item.id);
    setFlag(true);
    setModal2Open(true);
    setName(item.name);
    setOrganization(item.oid);
    setCount(item.count);
    setDesc(item.desc);
    setStatus(item.status);
  };

  const del = async (item: any) => {
    let {
      data: { code, msg },
    } = await axios.delete('ljt_delRole?id=' + item.id);
    if (code === 200) {
      getData();
    }
  };

  const falseStatus = async (item: any) => {
    let {
      data: { code, msg },
    } = await axios.post('ljt_updateRoleStatus', {
      id: item.id,
      status: false,
    });
    if (code === 200) {
      getData();
    }
  };

  const trueStatus = async (item: any) => {
    let {
      data: { code, msg },
    } = await axios.post('ljt_updateRoleStatus', { id: item.id, status: true });
    if (code === 200) {
      getData();
    }
  };

  useEffect(() => {
    getOrganization();
    getData();
  }, []);

  const [searchName, setSearchName] = useState('');
  const [searchOrganization, setSearchOrganization] = useState('请选择部门');

  return (
    <div className="roleManage">
      <div className="header">
        <div
          style={{
            width: '70%',
            height: '100%',
            display: 'flex',
            justifyContent: 'space-between',
            alignItems: 'center',
          }}
        >
          <span>
            角色名称：
            <Input
              placeholder="请输入角色名称"
              value={searchName}
              onChange={(e) => setSearchName(e.target.value)}
            />
          </span>
          <span>
            部门：
            <Select
              style={{ width: 120 }}
              allowClear
              value={searchOrganization}
              onChange={(e) => setSearchOrganization(e)}
              options={organizations}
              placeholder="请选择部门"
            />
          </span>
          <Button
            type="primary"
            onClick={() => {
              getData();
            }}
          >
            查询
          </Button>
          <Button
            onClick={() => {
              setSearchName('');
              setSearchOrganization('请选择部门');
            }}
          >
            重置
          </Button>
        </div>
      </div>
      <div className="content">
        <div style={{ marginBottom: '20px' }}>
          <Button onClick={() => setModal2Open(true)}>新建角色</Button>
          <span style={{ float: 'right' }}>
            <Button>导入</Button>
            <Button>导出</Button>
          </span>
        </div>
        <Table columns={columns} dataSource={data} />
      </div>

      <Modal
        title="新建角色"
        centered
        open={modal2Open}
        onOk={() => submit()}
        onCancel={() => cancel()}
      >
        <div>
          <p>
            角色名称：
            <Input
              value={name}
              placeholder="请输入角色名称"
              onChange={(e) => setName(e.target.value)}
            />
          </p>
          <p>
            所属部门：
            <Select
              style={{ width: 120 }}
              allowClear
              value={organization}
              onChange={(e) => setOrganization(e)}
              options={organizations}
              placeholder="请选择部门"
            />
          </p>
          <p>
            角色人数：
            <Input
              value={count}
              onChange={(e) => setCount(e.target.value)}
              placeholder="请输入需要的角色人数"
            />
          </p>
          <p>
            角色描述：
            <TextArea
              rows={2}
              value={desc}
              placeholder="请添加角色描述"
              onChange={(e) => setDesc(e.target.value)}
            />
          </p>
          <p>
            角色状态：
            <Select
              style={{ width: 120 }}
              allowClear
              options={[
                { value: true, label: '启用' },
                { value: false, label: '停用' },
              ]}
              value={status}
              onChange={(e) => setStatus(e)}
            />
          </p>
        </div>
      </Modal>
    </div>
  );
}
